package com.englisheveryday.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.englisheveryday.R;
import com.englisheveryday.activity.CategoryDialog.OnDialogItemClickListener;
import com.englisheveryday.constants.Constants;
import com.englisheveryday.media.RichMediaPlayer;
import com.englisheveryday.service.ArticleService;
import com.englisheveryday.utils.ActivityManager;
import com.englisheveryday.utils.EnvironmentCheckUtil;
import com.englisheveryday.utils.L;
import com.englisheveryday.vo.ArticleVO;

public class ArticleActivity extends Activity {

	private Handler handler;
	private ListView articleListView;
	private ThreadPoolExecutor executor;
	private ArticleListViewAdapter adapter;
	private int page = 0;
	private int pageSize = 10;
	private List<ArticleVO> articleVOList;
	private RichMediaPlayer player;
	private Button loadmoreButton;
	private ArticleService articleService;
	private ImageView articleRefresh,category;
	private Animation syncLoadingAnimation;
	private int retrycount;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityManager.add(this);
		// 去掉标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 防止休眠
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.article_activity);
		setViews();
		setListeners();
		//检查SD卡
		if(!EnvironmentCheckUtil.SDCardCheck()){
			Toast.makeText(this, R.string.sd_status_error,Toast.LENGTH_SHORT).show();
		}
		articleVOList = new ArrayList<ArticleVO>();
		handler = new EnglishEveryDayHandler();
		articleService = new ArticleService(ArticleActivity.this);
		// 线程池
		executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
		executor.execute(new EnglishEveryDayThread());
		
	}

	// 设置View
	private void setViews() {
		// 设置播放器
		player = new RichMediaPlayer(ArticleActivity.this);
		articleListView = (ListView) findViewById(R.id.article_listView);
		articleRefresh = (ImageView) findViewById(R.id.article_refresh);
		category = (ImageView)findViewById(R.id.article_category);
		//设置footview
		LinearLayout linearLayout = (LinearLayout)LayoutInflater.from(ArticleActivity.this).inflate(R.layout.loadmore, null);
		articleListView.addFooterView(linearLayout);
		loadmoreButton = (Button)linearLayout.findViewById(R.id.loadmore);
		LinearLayout playLinearLayout = (LinearLayout)findViewById(R.id.article_linearlayout);
		//添加播放按钮
		playLinearLayout.addView(player.getView(),1);
	}

	//开始动画
	private void startAnimation(){
		articleRefresh.setImageDrawable(getResources().getDrawable(R.drawable.wb_icon_refresh_loading));
		syncLoadingAnimation = AnimationUtils.loadAnimation(ArticleActivity.this, R.anim.title_refresh_loading);
		LinearInterpolator lin = new LinearInterpolator();
		syncLoadingAnimation.setInterpolator(lin);
		articleRefresh.startAnimation(syncLoadingAnimation);
		articleRefresh.setEnabled(false);
	}
	//关闭动画
	private void stopAnimation(){
		if(articleRefresh!=null)
			articleRefresh.clearAnimation();
		//恢复原来的图片
		articleRefresh.setEnabled(true);
		articleRefresh.setImageDrawable(getResources().getDrawable(R.drawable.wb_icon_refresh_nor));
	}
	
	// 设置监听器
	private void setListeners() {
		loadmoreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loadmoreButton.setText(R.string.list_loading);
				loadmoreButton.setEnabled(false);
				executor.execute(new EnglishEveryDayThread());
			}
		});
		//与服务器同步
		articleRefresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startAnimation();
				executor.execute(new EnglishEveryDaySyncThread());	
			}
		});
		articleListView
				.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long arg3) {

					}
				});
		articleListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View view, int position, long arg3) {
						final String id = articleVOList.get(position)
								.getId();
						final int p = position;
						AlertDialog.Builder builder = new AlertDialog.Builder(
								ArticleActivity.this);
						builder.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										articleService.delete(id);
										articleVOList.remove(p);
										handler.sendEmptyMessage(Constants.HANDLER_DATA_LOADED);
									}
								});
						builder.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {

									}
								});
						builder.setTitle("是否删除");
						builder.show();
						return false;
					}
				});
		category.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CategoryDialog dialog = new  CategoryDialog(ArticleActivity.this,articleService.findAllCategory());
				dialog.setOnDialogItemClickListener(new OnDialogItemClickListener() {
					@Override
					public void onItemClick(String id) {
						L.d("id"+id);
					}
				});
				Rect rect = new Rect();
				getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
				dialog.onMeasure(category,200,100,rect.top);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});
	}


	// 处理handler
	class EnglishEveryDayHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.HANDLER_DATA_LOADED: {
				//刷新列表
				refreshList();
				loadmoreButton.setEnabled(true);
				loadmoreButton.setText(R.string.list_loadmore);
			}
			break;
			case Constants.HANDLER_DATA_SYNC : {
				refreshList();
				handler.sendEmptyMessage(Constants.HANDLER_DATA_LOADING_STOP);
				}
			break;
			case Constants.HANDLER_DATA_LOADING_STOP : {
				stopAnimation();
				Toast.makeText(ArticleActivity.this,R.string.list_load_stop,Toast.LENGTH_SHORT).show();
				}
			break;
			case Constants.HANDLER_DATA_NODATA : {
				Toast.makeText(ArticleActivity.this,R.string.list_load_no_message,Toast.LENGTH_SHORT).show();
				loadmoreButton.setEnabled(true);
				loadmoreButton.setText(R.string.list_loadmore);
			}
			break;
			case Constants.HANDLER_DATA_NETWORKNOTAVAILABLE : {
				stopAnimation();
				Toast.makeText(ArticleActivity.this,R.string.network_notavailable,Toast.LENGTH_SHORT).show();
			}
			break;
			case Constants.HANDLER_DATA_RESYNC : {
				L.d("重新同步:"+retrycount);
				if(retrycount<=3){
					executor.execute(new EnglishEveryDaySyncThread());
					retrycount ++;
				}else{
					handler.sendEmptyMessage(Constants.HANDLER_DATA_NETWORKNOTAVAILABLE);
				}
			}
			break;
			}
		}
	}
	
	private void refreshList(){
		if (articleVOList == null) {
			L.d("列表文件未初始化");
			return;
		}
		if (adapter == null) {
			L.d("adapter1");
			adapter = new ArticleListViewAdapter(
					ArticleActivity.this, articleVOList,
					player);
			articleListView.setAdapter(adapter);
		} else {
			L.d("adapter2");
			adapter.notifyDataSetChanged();
		}
	}

	// Load线程
	class EnglishEveryDayThread implements Runnable {
		@Override
		public void run() {
			L.d("articleService"+articleService);
			List<ArticleVO> tempList = articleService.load(page*pageSize+"", pageSize+"");
			if(tempList!=null&&tempList.size()>0){
				articleVOList.addAll(tempList);
				page++;
				handler.sendEmptyMessage(Constants.HANDLER_DATA_LOADED);
			}else {
				handler.sendEmptyMessage(Constants.HANDLER_DATA_NODATA);
			}
			
		}
	}
	
	//sync线程
	class EnglishEveryDaySyncThread implements Runnable {
		@Override
		public void run() {
			//同步类别
			String status = articleService.syncCategory();
			//同步英语文章
			status = articleService.syncArticle();
			if(Constants.SYNC_STATUS_FAILURE.equals(status)){
				retrycount=0;
				handler.sendEmptyMessage(Constants.HANDLER_DATA_NETWORKNOTAVAILABLE);
				return;
			}
			if(Constants.SYNC_STATUS_READTIMEOUT.equals(status)){
				handler.sendEmptyMessage(Constants.HANDLER_DATA_RESYNC);
				return;
			}
			if(Constants.SYNC_STATUS_SUCCESS.equals(status)){
				retrycount=0;
				articleVOList.clear();
				page = 0;
				List<ArticleVO> tempList = articleService.load(page*pageSize+"", pageSize+"");
				if(tempList!=null&&tempList.size()>0){
					articleVOList.addAll(tempList);
					page++;
				}
				handler.sendEmptyMessage(Constants.HANDLER_DATA_SYNC);
			}else {
				retrycount=0;
				handler.sendEmptyMessage(Constants.HANDLER_DATA_LOADING_STOP);
			}
		}
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		player.release();
	}
	
}